<?php
/**
 * FP_Tagger class file
 * @package FlickrPhotosets
 */

/**
 * This class is used for tagging photos.
 * 
 * @package FlickrPhotosets
 * @author Brad Dougherty <bdougherty@gmail.com>
 * @version 8.5.14
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License 3.0
 */
class FP_Tagger extends FlickrPhotosets {
	
	/**
	 * The user's Flickr Photosets configuration
	 * @var array
	 */
	public $pid;
	
	const tag_remove = 'remove';
	const tag_add = 'add';
	
	/*
	
	Up to 3 tags will be added to each photo is tagged in Facebook:
	
	fb:user=[uid]
	fb:tag=[uid/text],[x%],[y%]
	xmlns:fb=http://bdougherty.net/fbns
	
	The fb:user tag is required for the photo to show up in the 'photos of' pages.
	If the fb:tag is missing, the owner will be alerted to retag so we get the location.
	The fb:user tag is omitted if the tag is not for a facebook user.
	
	Information that must be posted to add a tag:
		method => add_tag
		uid => the uid of the photo's owner
		pid => the photo id
		token => sha512(owner_uid.pid.secret)
			!! Need to come up with a way to also check the following variables
		tag => the uid of the person to be tagged (or empty)
		tag_content => the tag string (or person's name)
		tag_x => the x pct of the center of the tag
		tag_y => the y pct of the center of the tag
	
	Information that must be posted to remove a tag/tags:
		method => remove_tag
		uid => the uid of the photo's owner
		pid => the photo id
		token => sha512(owner_uid.pid.secret.tag_ids)
		tag_ids => comma separated list of tag ids
		
	*/
	
	/**
	 * Calls the parent constructor.
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 */
	public function __construct() {
		// Initiate the connection to the database
		$this->connect_db();
		
		// Get properties from Facebook
		$this->facebook = new Facebook(FACEBOOK_API_KEY, FACEBOOK_API_SECRET);
		$this->get_app_properties();
		
		// Create the logger
		$this->log = new FP_Logger($this->_db);
		
		// Get the user's information
		$this->uid = (!empty($_GET['uid'])) ? $_GET['uid'] : $_POST['uid'];
		$this->get_info();
		
		// Initialize Flickr
		$this->init_flickr(false, false, false, true);
		$this->flickr->setToken($this->config['flickr_token']);
		
		// Get the photo
		$this->pid = (!empty($_GET['pid'])) ? $_GET['pid'] : $_POST['pid'];
		$this->tags = $this->flickr->tags_getListPhoto($this->pid);
	}
	
	/**
	 * Check to make sure the token is correct
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @return boolean True if correct
	 */
	private function _check_token($token, $type = self::tag_add, $data = '') {
		$check_token = ($type == self::tag_remove) ? $this->_get_remove_token($data) : $this->_get_add_token();
		if ($token == $check_token) {
			return true;
		}
		return false;
	}
	
	/**
	 * Calculates the token for tag addition
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @return string The token
	 */
	private function _get_add_token() {
		return hash(FlickrPhotosets::hash_method, $this->uid.$this->pid.FACEBOOK_API_SECRET);
	}
	
	/**
	 * Calculates the token for tag removal
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @param string $tag_ids Comma-separated string of tag_ids
	 * @return string The token
	 */
	private function _get_remove_token($tag_ids) {
		return hash(FlickrPhotosets::hash_method, $this->uid.$this->pid.FACEBOOK_API_SECRET.$tag_ids);
	}
	
	/**
	 * Adds the proper tags to the photo.
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @return boolean Success of the tag add
	 */
	public function add_tags() {
		if ($this->_check_token($_POST['token'])) {
			
			// This tag is a user
			if (is_numeric($_POST['tag'])) {
				$user_tag = '"fb:user='.$_POST['tag'].'"';
				$loc_tag = '"fb:tag='.$_POST['tag'].','.$_POST['tag_x'].','.$_POST['tag_y'].'"';
				$tag = $user_tag.' '.$loc_tag;
			}
			// This tag is a string
			else {
				$sanitized_string = str_replace('=', '+', str_replace(':', '+', $_POST['tag_content']));
				$tag = '"fb:tag='.$sanitized_string.','.$_POST['tag_x'].','.$_POST['tag_y'].'"';
			}
			
			// Not the owner, so we will queue up the tags
			if ($this->uid != $_POST['fb_sig_user']) {
				
				// Queue the tags (a notification will be sent later)
				$this->_db->add_tag_to_queue($this->uid, $tag);
				
				return array(
					'success' => 1,
					'title' => 'Yay!',
					'fbml_content' => '<fb:name uid="'.$this->uid.'" firstnameonly="true" linked="false" /> will be asked to approve the tag before anyone else can see it.',
					'button' => 'Close'
				);
			}
			
			// Owner is adding the tag
			if ($this->flickr->photos_addTags($this->pid, $tag)) {
				
				$this->log->tag_add($this->uid, $this->pid, $tag);
				
				// Notify the person that they were tagged
				if (is_numeric($_POST['tag_content'])) {
					//FP_Notifier::notify_tagged_user($_POST['tag_content']);
				}
								
				// Get a list of the tags (because we need to send back the ID)
				// Note: It would be nice if Flickr gave us back the ID of the tag when we add it...
				$tags = $this->flickr->tags_getListPhoto($this->pid);
				$last_tag = array_pop($tags);
				
				// We will also return the tagged user string
				$tagged_users = FlickrPhotosetsPhoto::get_tagged_users($this->pid, $this->config['flickr_token']);
				$tagged_users_string = FlickrPhotosetsPhoto::get_tagged_users_string($this->uid, $this->pid, $tagged_users);
				$tagged_users_string = str_replace('{canvasURL}', $this->canvas_url, $tagged_users_string);
				$tagged_users_string = str_replace('{callbackURL}', $this->callback_url, $tagged_users_string);
				
				return array(
					'success' => 1,
					'tag' => $_POST['tag'],
					'tagContent' => $_POST['tag_content'],
					'tagX' => $_POST['tag_x'],
					'tagY' => $_POST['tag_y'],
					'tags' => $tag,
					'tagID' => $last_tag['id'],
					'fbml_taggedUsersString' => $tagged_users_string
				);
				
			}
			
		}
		return false;
	}
	
	/**
	 * Enables tagging for the user
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @return string The dialog response
	 */
	public function enable_tagging() {
		
		// Validate the token
		if ($_POST['token'] == md5($this->uid.FACEBOOK_API_SECRET)) {
			
			$this->config['enable_tagging'] = 1;
			if ($this->save_config()) {
				return '<fb:dialogresponse><fb:dialog-title>Tagging Enabled!</fb:dialog-title><fb:dialog-content><p>Tagging is now enabled!</p></fb:dialog-content><fb:dialog-button type="button" value="Close" href="'.$_GET['redir'].'" /></fb:dialogresponse>';
			}
			else {
				return '<fb:dialogresponse><fb:dialog-title>Error</fb:dialog-title><fb:dialog-content><p>There was a problem when trying to enable tagging in your preferences. Please go to the configuration page and enable it manually.</p></fb:dialog-content><fb:dialog-button type="button" value="Close" href="'.$this->canvas_url.'/configure.php#features" /></fb:dialogresponse>';
			}
			
		}
		// Not the user
		else {
			return '<fb:dialogresponse><fb:dialog-title>Error</fb:dialog-title><fb:dialog-content><p>You aren\'t allowed to do that!</p></fb:dialog-content><fb:dialog-button type="button" value="Close" close_dialog="1" /></fb:dialogresponse>';
		}
		
	}
	
	/**
	 * Remove the specified tag from the photo.
	 *
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @param array $tag_ids Array of tag ids
	 * @param string $token The token
	 * @return boolean True if removed
	 */
	public function remove_tags() {
		$tag_ids = $_POST['tag_ids'];
		if ($this->_check_token($_POST['token'], self::tag_remove, $tag_ids)) {
			
			$tag_array = explode(',', $tag_ids);
			foreach ($tag_array as $tag) {
				$this->flickr->photos_removeTag($tag);
			}
			$this->log->tag_remove($this->uid, $this->pid, $tag_ids);
			
			// We will also return the tagged user string
			$tagged_users = FlickrPhotosetsPhoto::get_tagged_users($this->pid, $this->config['flickr_token']);
			$tagged_users_string = FlickrPhotosetsPhoto::get_tagged_users_string($this->uid, $this->pid, $tagged_users);
			$tagged_users_string = str_replace('{canvasURL}', $this->canvas_url, $tagged_users_string);
			$tagged_users_string = str_replace('{callbackURL}', $this->callback_url, $tagged_users_string);

			return array(
				'success' => 1,
				'tag_ids' => $tag_ids,
				'fbml_taggedUsersString' => $tagged_users_string
			);
			
		}
		return false;
	}
	
	/**
	 * Adds an item to a user's mini-feed when tagged in a photo.
	 * 
	 * 
	 * 
	 * @author Brad Dougherty <bdougherty@gmail.com>
	 * @param int $uid The Facebook uid of the actor
	 * @param string $session_key The actor's session key
	 * @param array $targets An array of the targets
	 * @param array $photos An array of the photos
	 * @return boolean True if the notification was sent.
	 */
	public static function tagged_user_notification($uid, $session_key, $targets, $photo) {
		
		/*
		
		// Create a Facebook object and set the user
		$facebook = new Facebook(FACEBOOK_API_KEY, FACEBOOK_API_SECRET);
		$facebook->set_user($uid, $session_key);
		
		// Set the templates
		$title_template = "{actor} tagged {target} in {photo}";
		$body_template = '{title}';
		
		// Multiple photos
		if (count($photos) > 1) {
			
		}
		// Single photo
		else {
			
			$target = implode(',', $targets);
			$title_data = json_encode(array(
				'photo' => 'a photo'
			));
			$body_data = json_encode(array(
				'title' => $photos[0]['title']
			));
			$image_1 = $photos[0]['image'];
			$image_1_link = $photos[0]['link'];
			
		}
		
		//$facebook->api_client->feed_publishActionOfUser('was tagged in a Flickr photo', '', $this->flickr->buildPhotoUrl($pid, "square"), $this->canvas_url.'/photos/'.$this->uid.'/'.$pid.'/');
		
		
		// One or multiple users tagged in multiple photos
		$target = $target;
		
		$title_data = json_encode(array(
			'photo' => $num.' photos'
		));
		
		$body_data = json_encode(array(
			'title' => $photo_title
		));
		$image_1 = 'http://farm1.static.flickr.com/40/84578358_4d10d53d63_t.jpg';
		$image_1_link = 'http://apps.facebook.com/flickrsetsbeta/photos/1470030056/84578358/';
		
		news feed:
			<Brad Dougherty> tagged <Amanda Kowalsky> in a photo.
		
		mini-feed:
			Brad tagged <Amanda Kowalsky> in 3 photos.
		
		
		// One or multiple users tagged in a single photo
		$target = $target;
		$title_template = "{actor} tagged {target} in {photo}";
		$title_data = json_encode(array(
			'photo' => 'a photo'
		));
		$body_template = '<b>{title}</b>';
		$body_data = json_encode(array(
			'title' => $photo_title
		));
		$image_1 = 'http://farm1.static.flickr.com/40/84578358_4d10d53d63_t.jpg';
		$image_1_link = 'http://apps.facebook.com/flickrsetsbeta/photos/1470030056/84578358/';
		
		news feed:
			<Brad Dougherty> tagged <Amanda Kowalsky> in a photo.
		
		mini-feed:
			Brad tagged <Amanda Kowalsky> in a photo.
			
		*/
		
	}
	
}

?>